package cn.org.wangchangjiu.redis.util;


import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import lombok.extern.slf4j.Slf4j;

/**
 * redisson分布式锁工具类
 *
 * @author zerozib
 * @date 2019-05-10 09:20
 */
@Slf4j
public class RedissonUtil {

    private static final String DEFAULT_LOCK_KEY = "LOCK_COMMON";

    /**
     * redisson客户端
     */
    private static RedissonClient client = RedisSpringUtils.getBean(RedissonClient.class);

    /**
     * 获取锁
     *
     * @param key
     *            锁key
     * @return 锁对象
     */
    public static RLock getLock(String key) {

        if (isEmpty(key)) {
            key = DEFAULT_LOCK_KEY;
        }

        return client.getLock(key);
    }

    /**
     * 释放锁
     *
     * @param lock
     *            锁对象
     * @param key
     *            锁key
     */
    public static void unlock(RLock lock, String key) {
        if (null != lock) {
            try {
                // 释放锁
                lock.unlock();
            } catch (Exception e) {
                log.error("释放锁{}失败", key);
            }
        }
    }

    private static boolean isEmpty(String str) {
        return null == str || "".equals(str);
    }
}
